<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Guacamole connection</title>
    {% load staticfiles %}
    <link rel="stylesheet" type="text/css" href="{% static 'plugins/sweetalert/sweetalert2.min.css' %}">
    <style>
        body {
            padding:0;  /*去除内边距*/
            border:0;   /*去除边框*/
            margin:0;   /*去除外边距*/
        }
    </style>
</head>
<body>
<!--<h1>Guacamole Remote Desktop</h1>-->
<!-- jQuery 2.2.3 -->
<script src="{% static "plugins/jQuery/jquery-2.2.3.min.js" %}"></script>
<!-- Guacamole -->
<script type="text/javascript" src="{% static 'plugins/guacamole/all.min.js' %}"></script>
<script type="text/javascript" src="{% static 'plugins/sweetalert/sweetalert2.all.min.js' %}"></script>
<script type="text/javascript" src="{% static 'plugins/mousetrap/mousetrap.min.js' %}"></script>
<script type="text/javascript" src="{% static 'plugins/clipboard.js/clipboard.min.js' %}"></script>


<!-- Matomo -->
<script type="text/javascript">
  var _paq = window._paq || [];
  /* tracker methods like "setCustomDimension" should be called before "trackPageView" */
  _paq.push(['trackPageView']);
  _paq.push(['enableLinkTracking']);
  (function() {
    var u="//193.112.194.114:8002/";
    _paq.push(['setTrackerUrl', u+'matomo.php']);
    _paq.push(['setSiteId', '1']);
    var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
    g.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'matomo.js'; s.parentNode.insertBefore(g,s);
  })();
</script>
<!-- End Matomo Code -->

 
<!-- Display -->
<div id="display">
</div>
<!-- Init -->
<script type="text/javascript">

    // convert unicode
    function encodeUnicode(str) {
        var res = [];
        for ( var i=0; i<str.length; i++ ) {
        res[i] = ( "00" + str.charCodeAt(i).toString(16) ).slice(-4);
        }
        return "\\u" + res.join("\\u");
    }

    // decode unicode
    function decodeUnicode(str) {
        str = str.replace(/\\/g, "%");
        return unescape(str);
    }

    // Get display div from document
    var display = document.getElementById("display");

    // Instantiate client, using an HTTP tunnel for communications.
    //http://guacamole.apache.org/doc/guacamole-common-js/Guacamole.WebSocketTunnel.html
    var ws_scheme = window.location.protocol == "https:" ? "wss" : "ws";
    var ws_path = ws_scheme + '://' + window.location.host + '/guacamole/{{token}}/';
    var tunnel = new Guacamole.WebSocketTunnel(ws_path);
    var guac = new Guacamole.Client(
       // new Guacamole.HTTPTunnel("tunnel")
        tunnel
    );

    // Add client to display div
    display.appendChild(guac.getDisplay().getElement());

    // Error handler
    guac.onerror = function(error) {
        console.log(error);
    };

    // Connect
    guac.connect();

    // Disconnect on close
    window.onunload = function() {
        guac.disconnect();
    }

    <!--console.log(guac);-->
    <!--console.log(tunnel);-->
    guac.onclipboard = function(stream, mimetype){
        var f;
        if (/^text\//.exec(mimetype)) {
            f = new Guacamole.StringReader(stream);
            var e = "";
            f.ontext = function (a) {
                e += a
            };
            f.onend = function () {
                document.getElementsByTagName('textarea').innerText =decodeUnicode(e);
            }
        }
    }
    <!--function rescale(browserDisp, guacDisp) {-->
        <!--var scale = Math.min(browserDisp.offsetWidth / Math.max(guacDisp.getWidth(), 1),-->
        <!--browserDisp.offsetHeight / Math.max(guacDisp.getHeight(), 1));-->
        <!--guacDisp.scale(scale);-->
    <!--}-->
    <!--guac.onresize = function(width,height){-->
        <!--console.log(width,height);-->
    <!--}-->
    <!--var guacDisplay = guac.getDisplay();-->
    <!--window.onresize = function(event) {-->
        <!--rescale(display, guacDisplay);-->
    <!--};-->
    //state change
    guac.onstatechange = function(state){
        if (state == 5){
            //alert closed
            //var STATE_IDLE          = 0;
            //var STATE_CONNECTING    = 1;
            //var STATE_WAITING       = 2;
            //var STATE_CONNECTED     = 3;
            //var STATE_DISCONNECTING = 4;
            //var STATE_DISCONNECTED  = 5;

            swal({
              title: 'Your connection has been lost or killed!',
              text: "Do you want to reconnect！",
              type: 'warning',
              showCancelButton: true,
              confirmButtonColor: '#3085d6',
              cancelButtonColor: '#d33',
              confirmButtonText: 'Reconnect',
              cancelButtonText: 'Cancel'
            }).then((result) => {
              if (result.value) {
                document.location.reload();
              }
            })

        }else if (state == 3){
            console.log(guac.getDisplay.size);
            guac.sendSize(window.innerWidth-10, window.innerHeight-60);
            $(window).resize(function(){
                guac.sendSize(window.innerWidth-10, window.innerHeight-60);
                <!--var guacDisplay = guac.getDisplay() -->
                <!--guacDisplay.resize(guacDisplay.getDefaultLayer(), window.innerWidth-10, window.innerHeight-40) -->
                <!--rescale(display, guacDisplay);-->
            });
        }
    }

    // Mouse
    var mouse = new Guacamole.Mouse(guac.getDisplay().getElement());

    mouse.onmousedown =
    mouse.onmouseup   =
    mouse.onmousemove = function(mouseState) {
        guac.sendMouseState(mouseState);
    };

    // Keyboard
    var keyboard = new Guacamole.Keyboard(document);

    keyboard.onkeydown = function (keysym) {
        guac.sendKeyEvent(1, keysym);
    };


    keyboard.onkeyup = function (keysym) {
            guac.sendKeyEvent(0, keysym);
    };

    function sendString(client, str) {
        for (var i=0; i < str.length; i++) {
            var codepoint = str.charCodeAt(i);
            var keysym;
            if (codepoint >= 0x0100)
                keysym = 0x01000000 | codepoint;
            else
                keysym = codepoint;
            client.sendKeyEvent(1, keysym);

        }
    }

    Mousetrap.bind('ctrl+shift+alt', function(e) {
        var data = document.getElementsByTagName('textarea').innerText;
        if (data == undefined){
            data = ''
        }
        swal({
          title: 'clipboard',
          input: 'textarea',
          confirmButtonText: 'copy to clipboard',
          inputValue: data,
          cancelButtonText: 'send data',
          <!--showCancelButton: true,-->
          <!--cancelButtonColor: '#d33',-->
        }).then(function(result) {
            if (result.value){
                var data = result.value;
                if (data != undefined){
                    var stream = guac.createClipboardStream("text/plain");
                    var writer = new Guacamole.StringWriter(stream);

                    // Send text chunks
                    for (var i = 0; i < data.length; i += 4096)
                    writer.sendText(data.substring(i, i + 4096));

                    // Close stream
                    writer.sendEnd();
                    guac.setClipboard(data);
                }
            }else if (result.dismiss === swal.DismissReason.cancel) {
                console.log(result.value);
          }

        })
    });
    var textarea = document.createElement("textarea");
    textarea.textContent = '';
    textarea.style.display = "none";  // Prevent scrolling to bottom of page in MS Edge.
    textarea.setAttribute('id','textarea');
    document.body.appendChild(textarea);
</script>
</body>
</html>
